<template>
  <div demo-bg>
    <dv-scroll-board :config="config" style="width:95%;height:15vw;margin: 1vw" @mouseover="mouseoverHandler" @click="clickHandler" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import axios from 'axios';
import { useStore } from '@/store/index.js';

const config = reactive({
  header: ['ID', '土壤氮含量', '土壤钾含量', '土壤磷含量', '时间'],
  data: [],
  index: true,
  columnWidth: [50],
  align: ['center'],
});

// 假设你已经通过API获取了数据
const fetchData = async () => {
  try {
    const userStore = useStore();
    const token = userStore.token;
    const [soilNRes, soilPRes, soilKRes] = await Promise.all([
      axios.get('/api/soil/N/all?sensorType=Soil_N',{
        headers: {
          Authorization: `Bearer ${token}`,
        },
      }),
      axios.get('/api/soil/K/all?sensorType=Soil_K',{
        headers: {
          Authorization: `Bearer ${token}`,
        },
      }),
      axios.get('/api/soil/L/all?sensorType=Soil_L',{
        headers: {
          Authorization: `Bearer ${token}`,
        },
      }),
    ]);

    const soilNData = soilNRes.data;
    const soilPData = soilPRes.data;
    const soilKData = soilKRes.data;

    // 确保数据是数组
    if (Array.isArray(soilNData) && Array.isArray(soilPData) && Array.isArray(soilKData)) {
      const combinedData = combineData(soilNData, soilPData, soilKData);
      config.data = combinedData;
    } else {
      console.error('API返回的数据格式不正确');
    }
  } catch (error) {
    console.error('数据获取失败:', error);
  }
};

// 合并数据
const combineData = (soilNData, soilPData, soilKData) => {
  // 数据合并
  const combined = [];

  soilNData.forEach((soilN, index) => {
    const soilP = soilPData[index] || {};
    const soilK = soilKData[index] || {};

    combined.push([
      soilN.id,
      soilN.value,
      soilP.value || '-',
      soilK.value || '-',
      formatDate(new Date(soilN.createdAt)),
    ]);
  });

  return combined;
};

// 格式化时间为 'YYYY-MM-DD HH:mm'
const formatDate = (date) => {
  const pad = (num) => (num < 10 ? '0' + num : num);
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
};

// 调用fetchData获取数据
fetchData();

const mouseoverHandler = (e: any) => {
  console.log(e);
};

const clickHandler = (e: any) => {
  console.log(e);
};
</script>

<style scoped>
/* 样式可以根据需要调整 */
</style>
